# src/project_installer.py
import os
import re
from typing import Optional, Dict

def _has_make_install(makefile_path: str) -> bool:
    try:
        with open(makefile_path, "r", encoding="utf-8", errors="ignore") as f:
            txt = f.read()
        # 极简：匹配行首的 install: 目标
        return re.search(r"(?m)^\s*install\s*:", txt) is not None
    except Exception:
        return False

def _has_install_sh(root: str) -> Optional[str]:
    for name in ("install.sh", "scripts/install.sh"):
        p = os.path.join(root, name)
        if os.path.isfile(p):
            return p
    return None

def detect_project_installer(project_root: str) -> Optional[Dict]:
    """
    返回一个 plan:
      {
        "kind": "make" | "shell",
        "installer_cmd": 'make install' 或者 'bash install.sh',
        "strip_sudo": True/False
      }
    若无法探测到，返回 None
    """
    root = os.path.abspath(project_root)
    # 1) Makefile install
    mk = os.path.join(root, "Makefile")
    if os.path.isfile(mk) and _has_make_install(mk):
        # 许多项目在 Docker 内不需要 sudo，我们在 Dockerfile 里统一做一次 sed 去掉 sudo
        return {"kind": "make", "installer_cmd": "make install", "strip_sudo": True}

    # 2) install.sh
    # ish = _has_install_sh(root)
    # if ish:
    #     return {"kind": "shell", "installer_cmd": f"bash {os.path.relpath(ish, root)}", "strip_sudo": True}

    return None
